<template>
	<view class="page-wrapper">
		<!-- <view class="close-page" @tap="handleJump" data-type="BACK"><text class="fu-iconfont">&#xe7be;</text></view> -->

		<!-- 头部 -->
		<view class="page-header">
			<image class="logo" mode="aspectFill" :src="SYSTEM_CONFIG.logo"></image>
		</view>

		<!-- 密码登录 -->
		<view class="form-wapper" v-if="loginType === 'password'">
			<view class="form-w-num">
				<image class="xs-phhone" src="../../../static/xs_icon/phone1.png" mode=""></image>
				<view class="phone input-wapper">
					<view class="mobile rside">
						<input :focus="isMobile.focus" @blur="loseFocus('mobile')" @input="enterAccount('mobile')"
							placeholder-class="input-placeholder" type="number" v-model="account" placeholder="请输入手机号"
							maxlength="11" />
						<image v-show="isMobile.delete" @click="onDelete('mobile')" class="close"
							src="../../../static/empty/close.png" mode=""></image>
					</view>
				</view>
			</view>
			<view class="form-w-password">
				<image class="xs-sec" src="../../../static/xs_icon/password.png" mode=""></image>
				<!-- <view class="title">密码</view> -->
				<view class="code input-wapper">
					<view class="rside">
						<input :focus="isPassword.focus" @blur="loseFocus('password')" @input="enterAccount('password')"
							placeholder-class="input-placeholder" v-if="passwordInputType == 'password'" type="password"
							v-model="password" placeholder="请输入密码(6-12位数字及字母) " maxlength="12" />
						<input :focus="isPassword.focus" @blur="loseFocus('password')" @input="enterAccount('password')"
							placeholder-class="input-placeholder" v-if="passwordInputType == 'text'" type="text"
							v-model="password" placeholder="请输入密码(6-12位数字及字母) " maxlength="12" />
						<image v-show="isPassword.delete" @blur="loseFocus('password')" @click="onDelete('password')"
							class="close" src="../../../static/empty/close.png" mode=""></image>
					</view>
					<view class="eye" @tap="handleTogglePasswordInputType">
						<text class="fu-iconfont" v-if="passwordInputType == 'password'">&#xe7e9;</text>
						<text class="fu-iconfont" v-if="passwordInputType == 'text'">&#xe7e6;</text>
					</view>
				</view>
			</view>
			<!-- <view class="paw">
        <view class="btn" @tap="loginType = 'code'">验证码登录</view>
      </view> -->
		</view>

		<!-- 验证码登录 -->
		<!-- <view class="form-wapper" v-if="loginType === 'code'">
      <view class="title">账号</view>
      <view class="phone input-wapper">
        <view class="mobile rside">
          <input placeholder-class="input-placeholder" type="number" value="" v-model="phone" placeholder="请输入手机号" />
        </view>
      </view>
      <view class="title mt30">验证码</view>
      <view class="code input-wapper">
        <view class="rside">
          <input placeholder-class="input-placeholder" type="number" value="" v-model="vercode" placeholder="验证码" />
        </view>
        <button class="get-code-btn" type="default" :loading="verCodeBtnLoading" @tap="handleSendVerCode">{{beginning ? '倒计时' + time + 's' : '获取验证码'}}</button>
      </view>
      <view class="paw">
        <view class="btn" @tap="loginType = 'password'">密码登录</view>
      </view>
    </view> -->

		<!-- 登录按钮 -->
		<view class="login-btn-wrapper">
			<button class="login-btn" style="margin-bottom: 10px;" :loading="loginBtnLoading"
				@tap="handleLogin">登录</button>
			<!-- <button class="login-btn" :class="{'btnFalse':!agreement}" style="margin-bottom: 10px;" :loading="loginBtnLoading" @tap="handleLogin" :disabled="!agreement">登录</button> -->
			<!-- <button class="login-btn" :loading="loginBtnLoading2" @tap="handleLogin2">一键登录</button> -->
		</view>

		<!-- 忘记密码、注册账号 -->
		<view class="reg-paw">
			<text @tap="handleJump" :data-url="`${PAGE_BASE_URL}register/index`">注册账号</text>
			<text class="register"></text>
			<text @tap="handleJump" :data-url="`${PAGE_BASE_URL}forget-password/index`">忘记密码</text>
		</view>

		<!-- 快捷登录 -->
		<!-- <view class="quick">
      <view class="quick-title"><text class="line"></text><text class="txt">快捷登录</text><text class="line"></text></view>
      <view class="quick-icons">
        <image :src="STATIC_IMAGE_BASE_URL + '/login/login-quick-001.png'" mode="" @tap="handleLoginUseWechat"></image>
        <image :src="STATIC_IMAGE_BASE_URL + '/login/login-quick-002.png'" mode="" @tap="handleLoginUseQQ"></image>
      </view>
    </view> -->
		<!-- <view class="agreement">
      <image v-if="!agreement" src="../../../static/xs_icon/chose.png" mode="" @click="onAgreement()"></image>
      <image v-else src="../../../static/xs_icon/shoseSel.png" mode="" @click="onAgreement()"></image>
      点击查看
      <text @tap="handleJump" data-url="/pages/agreement?data=user_agreement">《用户协议》</text>
    </view> -->
	</view>
</template>
<script>
	import {
		validate
	} from '@/common/utils/index';
	import {
		SYSTEM_CONFIG
	} from '@/common/config.js';
	let _this;
	export default {
		data() {
			return {
				isMobile: {
					focus: false,
					delete: false
				},
				isPassword: {
					focus: false,
					delete: false
				},
				SYSTEM_CONFIG, // 系统配置

				/*================================================
        =            使用此模板你需要修改的参数            =
        =================================================*/

				STATIC_IMAGE_BASE_URL: '/fu-templete/static/', // 图片基础路径
				PAGE_BASE_URL: '/pages/login/', // 页面基础路径
				OPEN_PUSH_AUTH: true, // 是否开启推送

				/*=====  End of 使用此模板你可能需要改到的参数  ======*/

				loginType: 'password', // code 验证码登录  password 密码登录
				passwordInputType: 'password', // 密码输入框类型 用于显示隐藏密码

				phone: '', // 手机号
				vercode: '', // 验证码
				account: '', // 账号
				password: '', // 密码

				loginBtnLoading: false, // 登录按钮加载动画
				loginBtnLoading2: false, //一键登录加载动画
				verCodeBtnLoading: false, // 获取验证码按钮动画

				/*========================================
        =            发送验证码所需参数            =
        =========================================*/

				time: 60,
				beginning: false,

				/*=====  End of 发送验证码所需参数  ======*/
				agreement: false
			};
		},

		onLoad() {
			_this = this;
			this.userState();
		},

		methods: {
			enterAccount(e) {
				if (e == 'mobile') {
					if (this.account != '') {
						this.isMobile.delete = true;
					} else {
						this.isMobile.delete = false;
					}
				} else if (e == 'password') {
					if (this.password != '') {
						this.isPassword.delete = true;
					} else {
						this.isPassword.delete = false;
					}
				}
			},
			onDelete(e) {
				if (e == 'mobile') {
					this.account = '';
					this.isMobile.focus = true;
					this.isMobile.delete = false;
				} else if (e == 'password') {
					this.password = '';
					this.isPassword.focus = true;
					this.isPassword.delete = false;
				}
			},
			loseFocus(e) {
				if (e == 'mobile') {
					// console.log(111111)
					this.isMobile.focus = false;
				} else if (e == 'password') {
					this.isPassword.focus = false;
				}
			},
			//  xs 用户状态
			userState() {
				const USER_INFO = uni.getStorageSync('USER_INFO');
				console.log(USER_INFO);
				if (USER_INFO != '') {
					uni.switchTab({
						url: '../../my/index/index'
					});
				}
				// const { user_token, address } = uni.getStorageSync('USER_INFO');
				// this.$store.state.userInfo = uni.getStorageSync('USER_INFO');
				// if (user_token != undefined) {
				// 	if (address == '') {
				// 		uni.redirectTo({
				// 			url: '../fill-in-data/fill-in-data'
				// 		});
				// 	} else {
				// 		uni.switchTab({
				// 			url: '../../news/news/news'
				// 		});
				// 	}
				// }
			},
			// xs 获取绑定账户状态
			postStatus() {
				this.$api
					.post(global.apiUrls.my.accountStatus)
					.then(res => {
						console.log(res);
						if (res.data.code == 1) {
							const userInfo = uni.getStorageSync('USER_INFO');
							userInfo.alipay = res.data.data.alipay;
							userInfo.wechat = res.data.data.wechat;
							uni.setStorageSync('USER_INFO', userInfo);
						}
					})
					.catch(err => {
						// this.$popup.showToast('保存失败')
					});
			},

			// 账号密码登录
			handleLogin() {
				if (this.loginBtnLoading) return false;
				let {
					loginType,
					phone,
					vercode,
					account,
					password,
					OPEN_PUSH_AUTH
				} = this;
				let clientId = 'clientId';
				let appSystem = 'appSystem';
				// #ifdef APP-PLUS
				if (OPEN_PUSH_AUTH) {
					clientId = plus.device.imei;
					// clientId = plus.push.getClientInfo().clientid || '';
					appSystem = uni.getSystemInfoSync().platform == 'ios' ? 1 : 2;
					// console.log("=================================================");
					// console.log(plus.device);
					// console.log(clientId);
				}
				// #endif
				if (loginType === 'password') {
					if (!validate(account, 'phone')) return this.$message.info('请正确输入手机号');
					if (!validate(password, 'password')) return this.$message.info('请正确输入密码');
					this.loginBtnLoading = true;
					this.$api
						.post(global.apiUrls.postloginByAccount, {
							mobile: account,
							password,
							client_id: clientId
							// client_id: ' ',
							// xs
							// client_id: 'fb2bb8acf006ce81ce6175188b5555a3',	// ios
							// client_id: 'e4e110115f24f6c4be1ec1bdd7a4c487',  	// 安卓
							// xj
							// client_id: '860746048383654,860746048383647',
						})
						.then(res => {
							this.loginBtnLoading = false;
							this._loginSuccess(res);
						})
						.catch(err => {
							this.loginBtnLoading = false;
						});
				} else {
					if (!validate(phone, 'phone')) return this.$message.info('请正确输入手机号');
					if (!vercode) return this.$message.info('请正确输入验证码');
					this.loginBtnLoading = true;
					this.$api
						.post(global.apiUrls.user_mobile_login, {
							mobile: phone,
							code: vercode
						})
						.then(res => {
							this.loginBtnLoading = false;
							this._loginSuccess(res);
						})
						.catch(err => {
							this.loginBtnLoading = false;
						});
				}
			},
			handleLogin2() {
				this.loginBtnLoading2 = true;

				let _this = this;
				const aliLoginPush = uni.requireNativePlugin('BenBen-AliLoginPush'); //安卓
				const dariusPayPal = uni.requireNativePlugin('BenBen-AliLogin'); //ios
				aliLoginPush.show({
						command: 'login',
						userAgreement: 'http://yinsi.zzyyt.cn/yinsi.html',
						privacyAgreement: 'http://yinsi.zzyyt.cn/yinsi.html',
						key: 'k/IxDXqoJVFBeZdjtT3AHlcXWjGWJZuXlg8mScnQZ1IzmlR/7paH860N62ucdR+5CItsvGW/yUtAWJcLGOfNro9zyB6NEkKwUsqSKLcITv/FtJRU5uEK3DiG4B/chNDQNJ8Q79jgr4R6q4TsPmUYyTxOx4ndr+ai9aQGQ+5ZHa7aB0zJEp+4qQ6qaczGsCXCuJ1aTop4cAC974VXCzkqcGXf31hXj50DAnRXyXyb+pS+4tyPDv27Gnk87Hxr1HOW9XKe43CPT4oaQxm2aBvLUB5GZr2Iv4SN'
					},
					result => {
						if (result.ret) {
							// 点击一键登录按钮 获取到token 进行注册
							if (JSON.parse(result.ret).code == 600000 || JSON.parse(result.ret).resultCode == 600000) {
								this.$api
									.post(global.apiUrls.loginCode, {
										access_token: JSON.parse(result.ret).token
									})
									.then(res => {
										this.loginBtnLoading2 = false;
										this._loginSuccess(res);
									})
									.catch(err => {
										this.loginBtnLoading2 = false;
									});
							} else if (JSON.parse(result.ret).code == 600001 || JSON.parse(result.ret).resultCode ==
								600001) {
								// 唤起成功
								_this.$message.msg('唤起成功');
							} else {
								_this.$message.msg('请求超时，请稍后重试');
								// 唤起失败
							}
						} else {
							switch (result.type) {
								case 'register':
									// 点击注册按钮

									_this.$urouter.navigateTo({
										url: _this.PAGE_BASE_URL + 'register/index',
										params: {
											id: 1
										}
									});
									break;
								case 'accountLogin':
									// 点击手机号账号登录按钮
									_this.$urouter.navigateTo({
										url: _this.PAGE_BASE_URL + 'login/index',
										params: {
											id: 1
										}
									});
									break;
								case 'wechatLogin':
									// #ifdef APP-PLUS
									// uni.showToast({
									//   icon:"none",
									//   title: "暂未开通尽请期待"
									// })
									_this.handleLoginUseWechat();
									// #endif
									// #ifndef APP-PLUS
									uni.showToast({
										icon: 'none',
										title: '请在APP端进行操作'
									});
									// #endif
									break;
								case 'quickLogin':
									// 手机号快捷一键登录
									uni.showToast({
										icon: 'none',
										duration: 5000,
										title: '手机号快捷一键登录 ret:' + result.ret
									});
									this.loginBtnLoading2 = true;
									break;
								default:
									this.loginBtnLoading2 = true;
									uni.hideLoading();
									break;
							}
						}
					}
				);
				// 		dariusPayPal.show({
				// 		  "command": "login",
				// 		  "userAgreement": "http://yinsi.zzyyt.cn/yinsi.html",
				// 		  "privacyAgreement": "http://yinsi.zzyyt.cn/yinsi.html"
				// 		}, result => {

				// 		});
			},
			// 登录成功
			_loginSuccess(res) {
				console.log(res);
				this.$message.info(res.data.msg);
				if (res.data.code == 1) {
					global.token = res.data.data.userinfo.user_token;
					global.userInfo = res.data.data.userinfo;
					try {
						uni.setStorageSync('USER_TOKEN', global.token);
						uni.setStorageSync('USER_INFO', global.userInfo);
						uni.$emit('appLoginSuccess', {
							msg: '登录成功'
						});

						setTimeout(() => {
							uni.switchTab({
								url: '/pages/home/home/home'
							});
						}, 1000);

						// this.userState(); // xs 根据登录状态 跳转
						// this.postStatus(); // xs 获取绑定账户状态

						// userinfo:
						// address: ""
						// address_code: [""]
						// birthday: "2020-08-24"
						// client_id: null
						// head_img: "http://111.229.13.202:3210/static/admin/images/none.png"
						// id: 2
						// mobile: "184****6338"
						// sex: 0
						// user_level: 0
						// user_name: "用户51190"
						// user_nickname: "用户51190"
						// user_token: "f075dd90-243d-ef36-8b15-e8cdd84e5afe"
						// user_type: 0

						// setTimeout(() => {
						//   wx.navigateBack();
						// }, 1000)

						// _this.$urouter.navigateTo({
						//   url: '../fill-in-data/fill-in-data',
						//   params: {
						//     id: 1
						//   }
						// })
					} catch (e) {}
				}
			},

			// 微信登录
			handleLoginUseWechat() {
				let {
					OPEN_PUSH_AUTH
				} = this;
				let self = this;
				let clientId = 'clientId';
				let appSystem = 'appSystem';

				uni.login({
					provider: 'weixin',
					success: function(loginRes) {
						uni.getUserInfo({
							provider: 'weixin',
							success: function(infoRes) {
								uni.showLoading({
									title: '登录中'
								});

								// #ifdef APP-PLUS
								if (OPEN_PUSH_AUTH) {
									clientId = plus.push.getClientInfo().clientid || '';
									appSystem = uni.getSystemInfoSync().platform == 'ios' ? 1 : 2;
								}
								// #endif

								self.$api
									.post(global.apiUrls.loginByQuick, {
										type: 1,
										wx_unionid: infoRes.userInfo.unionId,
										qq_unionid: '',
										wb_unionid: '',

										clientId: clientId || '',
										appSystem: appSystem || '',
										nickname: infoRes.userInfo.nickName,
										avatar: infoRes.userInfo.avatarUrl,
										gender: infoRes.userInfo.gender
									})
									.then(res => {
										uni.hideLoading();
										self.otherLoginSuccess(res);
									})
									.catch(err => {
										uni.hideLoading();
									});
							}
						});
					}
				});
			},

			// QQ登录
			handleLoginUseQQ() {
				let {
					OPEN_PUSH_AUTH
				} = this;
				let self = this;
				let clientId = 'clientId';
				let appSystem = 'appSystem';

				uni.login({
					provider: 'qq',
					success: function(loginRes) {
						console.log(loginRes);
						uni.getUserInfo({
							provider: 'qq',
							success: function(infoRes) {
								uni.showLoading({
									title: '登录中'
								});

								// #ifdef APP-PLUS
								if (OPEN_PUSH_AUTH) {
									clientId = plus.push.getClientInfo().clientid || '';
									appSystem = uni.getSystemInfoSync().platform == 'ios' ? 1 : 2;
								}
								// #endif

								self.$api
									.post(global.apiUrls.loginByQuick, {
										type: 2,
										wx_unionid: '',
										qq_unionid: infoRes.userInfo.openId,
										wb_unionid: '',

										clientId: clientId || '',
										appSystem: appSystem || '',
										nickname: infoRes.userInfo.nickName,
										avatar: infoRes.userInfo.avatarUrl,
										gender: infoRes.userInfo.gender == '男' ? 1 : 0
									})
									.then(res => {
										uni.hideLoading();
										self.otherLoginSuccess(res);
									})
									.catch(err => {
										uni.hideLoading();
									});
							}
						});
					}
				});
			},

			// 第三方登陆登陆成功
			otherLoginSuccess(res) {
				if (res.data.code == 1) {
					if (res.data.data.userinfo.mobile) {
						global.token = res.data.data.userinfo.token;
						global.userInfo = res.data.data.userinfo;

						try {
							uni.setStorageSync('USER_TOKEN', global.token);
							uni.setStorageSync('USER_INFO', global.userInfo);
							uni.$emit('appLoginSuccess', {
								msg: '登录成功'
							});
							setTimeout(() => {
								uni.navigateBack();
							}, 1000);
						} catch (e) {}
					} else {
						global.tempUserLoginInfo = res.data.data;
						this.$urouter.redirectTo(this.PAGE_BASE_URL + 'bind-phone/index');
					}
				}
			},

			// 切换密码输入框类型
			handleTogglePasswordInputType() {
				this.passwordInputType = this.passwordInputType == 'password' ? 'text' : 'password';
			},

			// 发送验证码
			handleSendVerCode() {
				if (this.verCodeBtnLoading) return false;
				let {
					phone
				} = this;
				if (!validate(phone, 'phone')) return this.$message.info('请正确输入手机号');
				if (this.beginning) return false;

				this.verCodeBtnLoading = true;
				this.$api
					.post(global.apiUrls.GetVerifyCode, {
						is_test: global.IS_DEV,
						mobile: phone,
						type: '3'
					})
					.then(res => {
						this.verCodeBtnLoading = false;
						if (res.data.code == 1) {
							this.$message.info('验证码已发送至手机' + phone + '请注意查收');
							// 显示倒计时
							this.beginning = true;

							// 开始倒计时
							this.timer = setInterval(() => {
								let tempTime = this.time;
								if (tempTime == 0) {
									// 倒计时结束
									clearInterval(this.timer);
									this.beginning = false;
									this.time = 60;
									return;
								}
								this.time--;
							}, 1000);
						} else {
							this.$message.info(res.data.msg);
						}
					})
					.catch(err => {
						this.verCodeBtnLoading = false;
					});
			},
			// 同意用户协议
			onAgreement() {
				this.agreement = !this.agreement;
			}
		}
	};
</script>
<style lang="scss">
	@import './index.scss';
</style>
